package com.joven.shelltest.controller;

import cn.hutool.core.bean.BeanUtil;
import com.joven.shelltest.dto.ProtectTagTreeVO;
import com.joven.shelltest.dto.QtmPlaceAddressTreeVO;
import com.joven.shelltest.service.ProtectTagService;
import com.joven.shelltest.service.QtmPlaceAddressService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 区县链式转换
 *
 * @Author: wzj
 * @Date: 2024/2/18 17:21
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/address")
public class AddressController {

    private final QtmPlaceAddressService qtmPlaceAddressService;

    private final static Long QZ_CODE = 330800000000L;

    @RequestMapping("/get")
    public List<QtmPlaceAddressTreeVO> getAddress(String code) {
        if (StringUtils.isEmpty(code)) {
            code = String.valueOf(QZ_CODE);
        }
        List<QtmPlaceAddressTreeVO> list = qtmPlaceAddressService.list().stream().map(val -> {
            QtmPlaceAddressTreeVO treeVO = new QtmPlaceAddressTreeVO();
            BeanUtil.copyProperties(val, treeVO);
            return treeVO;
        }).collect(Collectors.toList());

        Map<Long, List<QtmPlaceAddressTreeVO>> map = list.stream().collect(Collectors.groupingBy(QtmPlaceAddressTreeVO::getParentCode));

        list.forEach(val -> val.setChildren(map.get(val.getAddressCode())));
        //过滤出符合顶层父Id的所有数据，即所有数据都归属于一个顶层父Id
        String finalCode = code;
        return list.stream().filter(val -> Long.parseLong(finalCode) == val.getParentCode()).collect(Collectors.toList());
    }

    private final static Long PARENT_CODE = 0L;

    private final ProtectTagService protectTagService;

    @GetMapping(value = "/list")
    public List<ProtectTagTreeVO> queryPageList(Long code) {
        if (Objects.isNull(code)) {
            code = PARENT_CODE;
        }
        List<ProtectTagTreeVO> list = protectTagService.list().stream().map(val -> {
            ProtectTagTreeVO treeVO = new ProtectTagTreeVO();
            BeanUtil.copyProperties(val, treeVO);
            return treeVO;
        }).collect(Collectors.toList());
        Map<Long, List<ProtectTagTreeVO>> map = list.stream().collect(Collectors.groupingBy(ProtectTagTreeVO::getParentId));
        list.forEach(val -> val.setChildren(map.get(val.getId())));
        Long finalCode = code;
        return list.stream().filter(val -> finalCode.equals(val.getParentId())).collect(Collectors.toList());
    }
}
